<?php
namespace intelligent\vcard\services;

use Yii;
use intelligent\vcard\models\Vcard;
use intelligent\vcard\models\Collection;
use heihei\base\UserHintExitException;

/**
 * 电子名片
 *
 * @author dejin <ldj@hianto2o.com>
 */
class VcardService extends \services\Service
{
    /**
     * 还回当前框架版本号
     * @return bool 框架版本
     */
    public function save($params, $condition = null){
        $vcard = $condition ? static::getItem($condition) : new Vcard();

        if($condition && !$vcard){
            $conditionStr = is_object($condition)  ? json_encode($condition, JSON_UNESCAPED_UNICODE) : $condition;
            throw new UserHintExitException($conditionStr  . "未找到！");
        }
        
        $vcard->load($params, '');
        if(!$vcard->save()){
            return static::fail($vcard->getErrorMessage());
        }
        return true;
    }

    public function listByPage($params){
        return static::toListPage(Vcard::find(), $params);
    }

    public function getItem($condition){
        return Vcard::findOne($condition);
    }

    public function getDefault($userId){
        $vcard = Vcard::find()->where(['is_default'=>1,'user_id'=>$userId])->one();
        if($vcard){
            return $vcard;
        }

        return Vcard::find()->where(['user_id'=>$userId])->orderBy('id DESC')->one();
    }

    public function getMyCollection($userId){
        return Collection::find()->where(['user_id'=>$userId])->all();
    }

    public function star($userId, $toUserId, $fromUserId){
        $collectionQuery = Collection::find()->where(['user_id' => $userId, 'to_user_id' => $toUserId]);
        if($collectionQuery->one()){
            throw new UserHintExitException("已经关注不需要再关注");
        }
        $collection = new Collection;
        $collection->user_id = $userId;
        $collection->to_user_id = $toUserId;
        $collection->from_user_id = $fromUserId;
        $collection->save();

        if(!$collection->save()){
            throw new UserHintExitException($vcard->getErrorMessage());
        }
    }
}
